package com.jy.app.lib.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by jan on 2016/4/13.
 */
public class CommonDatabasesOpenhelper extends OrmLiteSqliteOpenHelper{
    private static final String TAG = "CommonDatabasesOpenhelper";
    private Map<String, Dao> mDaoMap = new HashMap<String, Dao>();

    public CommonDatabasesOpenhelper(Context context, String databaseName, int databaseVersion) {
        super(context, databaseName, null, databaseVersion);
    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        createAppData();
    }

    /**
     * 创建app的本地数据库和表资源
     */
    protected void createAppData(){};

    /**
     * 获取已有TABLE的实体DAO
     * @param clazz
     * @return
     */
    public synchronized Dao getDao(Class clazz) {
        Dao dao = null;
        try{
            String className = clazz.getSimpleName();

            if (mDaoMap.containsKey(className)) {
                dao = mDaoMap.get(className);
            }
            if (dao == null) {
                dao = super.getDao(clazz);
                mDaoMap.put(className, dao);
            }
        }catch (Exception e){
        }
        return dao;
    }


    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
    }

    @Override
    public void close() {
        super.close();
        for (String key : mDaoMap.keySet()) {
            Dao dao = mDaoMap.get(key);
            dao = null;
        }
    }
}
